<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
    >
          <!-- <el-form-item label="申请人" prop="userId">
            <UserSelect
              v-model="queryParams.userId"
              class="!w-240px"
              placeholder="请选择申请人"
              clearable
            />
          </el-form-item> -->
          <el-form-item label="任务号" prop="taskNumber">
            <el-input
                v-model="queryParams.taskNumber"
                placeholder="请输入任务号"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="任务名称" prop="taskName">
            <el-input
                v-model="queryParams.taskName"
                placeholder="请输入任务名称"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="任务类型" prop="taskType">
            <el-select
                v-model="queryParams.taskType"
                placeholder="请选择任务类型"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.OA_TASK_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="审批结果" prop="status">
            <el-select
                v-model="queryParams.status"
                placeholder="请选择审批结果"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item> -->
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker
                    v-model="queryParams.createTime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                    class="!w-220px"
                />
              </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <!-- <el-button plain type="primary" @click="handleCreate()">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button> -->
            </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
            <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
              <el-table-column label="任务号" align="center" prop="taskNumber" width="150" />
                
                <!-- <el-table-column label="负责人" align="center" prop="chargeUserName" width="90" /> -->
                <el-table-column label="任务名称" align="center" prop="taskName" />
                <el-table-column label="任务类型" align="center" prop="taskType">
                  <template #default="scope">
                    <dict-tag :type="DICT_TYPE.OA_TASK_TYPE" :value="scope.row.taskType" />
                  </template>
                </el-table-column>
                <el-table-column label="收费金额" align="center" prop="paymentAmount" />
                <!-- <el-table-column label="已收款" align="center" prop="paymentReceived">
                  <template #default="scope">
                    <dict-tag :type="DICT_TYPE.OA_IS_OR_NO" :value="scope.row.paymentReceived" />
                  </template>
                </el-table-column>
                <el-table-column label="收款日期" align="center" prop="paymentDate" />
                <el-table-column label="收费金额" align="center" prop="paymentAmount" />
                <el-table-column label="收款方式" align="center" prop="paymentMethod" />
                <el-table-column label="参与人员" align="center" prop="teamMemberNames" />
                <el-table-column label="公司信息" align="center" prop="companyInfo" /> -->
                <el-table-column label="任务状态" align="center">
                  <template #default="scope">
                    <dict-tag :type="DICT_TYPE.OA_TASK_STATUS" :value="scope.row.taskFinishStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="申请人" align="center" prop="userName" />
                <el-table-column label="审批结果" align="center" prop="status">
                  <template #default="scope">
                    <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="scope.row.status" />
                  </template>
                </el-table-column>
                <el-table-column
                    label="创建时间"
                    align="center"
                    prop="createTime"
                    :formatter="dateFormatter"
                    width="180px"
                />
    <el-table-column label="操作" align="center" width="180px" fixed="right">
      <template #default="scope">
        <el-button
            v-hasPermi="['bpm:process-instance:query']"
            size="small"
            type="primary"
            @click="handleProcessDetail(scope.row)"
        >
         <Icon class="mr-1px" icon="ep:coordinate" /> 审批
        </el-button> 
      </template>
    </el-table-column>
  </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>
 
  <ProcessInstanceDetailDrawer
    v-model="showDrawer"
    :process-instance-id="currentProcessInstanceId"
    title="流程进度"
    @success="handleDrawerSuccess"
  />
  <FinishTaskDialog
    v-model:visible="showFinishDialog"
    :row="finishRow"
    @confirm="onFinishDialogConfirm"
  />
</template>
<script lang="ts" setup>
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import { dateFormatter } from '@/utils/formatTime'
  import { MainTasksApi, MainTasksVO } from '@/api/oa/maintasks'
  import * as ProcessInstanceApi from '@/api/bpm/processInstance'
  import ProcessInstanceDetailDrawer from '@/views/bpm/processInstance/components/ProcessInstanceDetailDrawer.vue'
  import { useUserStore } from '@/store/modules/user'
  import FinishTaskDialog from './components/FinishTaskDialog.vue'
  
  defineOptions({ name: 'MainTasksTodo' })

  const message = useMessage() // 消息弹窗
  const router = useRouter() // 路由
  const { t } = useI18n() // 国际化
  const userStore = useUserStore()

  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const list = ref([]) // 列表的数据
  const queryParams = reactive({
      pageNo: 1,
    pageSize: 10,
    userId: undefined,
    taskNumber: undefined,
    taskName: undefined,
    taskType: undefined,
    status: undefined,
    createTime: [],
  })
  const queryFormRef = ref() // 搜索的表单

  const showDetailDrawer = ref(false)
  const currentTaskId = ref('')
  const showDrawer = ref(false)
  const currentProcessInstanceId = ref('')

  const showFinishDialog = ref(false)
  const finishRow = ref<MainTasksVO | null>(null)
  const finishLoading = ref(false)
  const finishFormData = ref({})

  /** 查询列表 */
  const getList = async () => {
    loading.value = true
    try {
              const data = await MainTasksApi.getMainTasksTodoPage(queryParams)
      list.value = data
      // total.value = data.total
    } finally {
      loading.value = false
    }
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  /** 添加操作 */
  const handleCreate = () => {
    router.push({ name: 'MainTasksCreate' })
  }

  /** 详情操作 */
  const handleDetail = (row: MainTasksVO) => {
    currentTaskId.value = String(row.id)
    showDetailDrawer.value = true
  }

  /** 取消请假操作 */
  const cancelProcess = async (row) => {
    // 二次确认
    const { value } = await ElMessageBox.prompt('请输入取消原因', '取消流程', {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
      inputErrorMessage: '取消原因不能为空'
    })
    // 发起取消
    await ProcessInstanceApi.cancelProcessInstanceByStartUser(row.id, value)
    message.success('取消成功')
    // 刷新列表
    await getList()
  }

  /** 审批进度 */
  const handleProcessDetail = (row) => {
    currentProcessInstanceId.value = String(row.processInstanceId)
    showDrawer.value = true
  }

  const handleDrawerSuccess = () => {
    showDrawer.value = false
    getList()
  }

  const handleFinishTask = (row: MainTasksVO) => {
    if(row.status!=2){
      message.success('审核通过才能修改主任务状态')
      return
    }
    finishRow.value = row
    showFinishDialog.value = true
  }

  const onFinishDialogConfirm = async (formData) => {
    if (!finishRow.value) return
    finishLoading.value = true
    try {
      await MainTasksApi.updateMainTasks({
        ...finishRow.value,
        taskFinishStatus: 1,
        paymentReceived: formData.paymentReceived,
        paymentDate: formData.paymentDate,
        paymentAmount: formData.paymentAmount,
        paymentMethod: formData.paymentMethod,
        collectionCompany: formData.collectionCompany,
        paymentCompany: formData.paymentCompany
      })
      message.success('操作成功')
      showFinishDialog.value = false
      getList()
    } finally {
      finishLoading.value = false
    }
  }

  // fix: 列表不刷新的问题。
  watch(
      () => router.currentRoute.value,
      () => {
        getList()
      }
  )

  /** 初始化 **/
  onMounted(() => {
    getList()
  })
</script>
